<template>
  <!--  echarts默认宽高为0-->
  <div id="demo" ref="salePic"></div>
</template>

<script>
import * as ECharts from 'echarts'
import { markRaw } from 'vue'
export default {
  name: "chartForms",
  props:['name','category','saleCount','sales'],
  data(){
    return{
      myEcharts:undefined,
    }
  },
  watch:{
    name:{
      immediate:true,
      handler(){
        this.$nextTick(()=>{
          this.createCharts()
        })
      }
    },
    category:{
      immediate: true,
      handler(){
        this.$nextTick(()=>{
          this.createCharts()
        })
      }
    }
  },
  unmounted() {
    window.removeEventListener("resize", this.handlerResize)
    if (!this.myEcharts.isDisposed()){
      this.myEcharts.dispose()

    }
  },
  methods:{
    handlerResize(){
      if (this.myEcharts!==undefined && !this.myEcharts.isDisposed()) {
        this.myEcharts.resize()
      }
    },
    createCharts(){
      if (this.myEcharts!==undefined && !this.myEcharts.isDisposed()){
        this.myEcharts.dispose()
      }
      this.myEcharts=markRaw(ECharts.init(this.$refs.salePic))
      window.addEventListener("resize", this.handlerResize)
      //设置参数
      let opt={
        xAxis:[
          {
            type: 'category',
            boundaryGap: true,
            data:this.category
          },
          {
            type: 'category',
            boundaryGap: true,
            data:this.category
          }
        ],
        yAxis:[
          {
            type: 'value',
            scale: true,
            name: this.name,
            min: 0,
            boundaryGap: [0.2, 0.2]
          },
          {
            type: 'value',
            scale: true,
            name: '变化率',
            min: -1,
            boundaryGap: [0.2, 0.2]
          }
        ],
        tooltip:{
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#283b56'
            }
          }
        },
        toolbox: {
          show: true,
          feature: {
            dataView: { readOnly: false },
            saveAsImage: {}
          }
        },
        dataZoom: {
          show: false,
          start: 0,
          end: 100
        },
        legend:{
          // left:'left',
          // orient:'vertical'
        },

        series: [
          {
            type: 'bar',
            name:this.name,
            data:this.saleCount
          },
          {
            xAxisIndex: 1,
            yAxisIndex: 1,
            type: 'line',
            name:'变化率',
            data:this.sales
          }
        ]
      }
      this.myEcharts.setOption(opt)
    }
  }
}
</script>

<style scoped>
#demo{
  /*width: 45%;*/
  height: 530px;
  border: 1px solid #c76e4d;
}
</style>
